--- 一颗象棋棋子
---@class NChess.Piece : Object
---@field public id integer
---@field public name string
---@field public whiteStr string
---@field public blackStr string
local Piece = class("NChess.Piece")

function Piece:initialize(id)
  self.id = id
  self.name = "unknown"
end

function Piece:getColor()
  if self.id > 0 then
    return "white"
  else
    return "black"
  end
end

---@param board integer[][] 表示棋盘的二维数组，内有棋子id或者0
---@param fromX integer
---@param fromY integer
---@param x integer
---@param y integer
---@return boolean, table|nil
function Piece:canMoveTo(board, fromX, fromY, x, y)
  return false
end

-- 判断棋子走到x y后会不会导致自己被将军
---@param board integer[][]
---@param fromX integer
---@param fromY integer
---@param x integer
---@param y integer
---@return boolean
function Piece:willBeChecked(board, fromX, fromY, x, y)
  local Ch = require "packages.chess-games.nchess"
  local id = self.id

  -- 拷贝棋盘
  local tmp = table.clone(board)

  -- 模拟走子（可能吃子）
  tmp[fromY][fromX] = 0
  tmp[y][x] = id

  -- 找到己方王的位置
  local kingId = (id > 0) and Ch.wK or Ch.bK
  local kingX, kingY
  for _y, xArr in ipairs(tmp) do
    for _x, _id in ipairs(xArr) do
      if _id == kingId then
        kingX = _x
        kingY = _y
        break
      end
    end
    if kingX then break end
  end

  -- 遍历敌方所有棋子，看能否攻击到王
  for _y, xArr in ipairs(tmp) do
    for _x, _id in ipairs(xArr) do
      if _id * id < 0 then
        local p = Ch:getPieceById(_id)
        if p:canMoveTo(tmp, _x, _y, kingX, kingY) then
          return true -- 被将军
        end
      end
    end
  end

  return false
end

-- board是否存在可以移动的点
---@param board integer[][]
function Piece:canMove(board, fromX, fromY)
  for y = 1, 8 do
    for x = 1, 8 do
      if self:canMoveTo(board, fromX, fromY, x, y) and not self:willBeChecked(board, fromX, fromY, x, y) then
        return true
      end
    end
  end

  return false
end

function Piece:clone(name, class)
  local newPiece = class:new()
  newPiece.name = name
  return newPiece
end


return Piece
